var infoType = "";
var oTable;

function formatDateTime(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
};
$(function () {
    gMainDT = $("#mainDataTable").DataTable({
        ajax: {
            url: "../rds_alarmManage/getDeviceRecord4DT",
            type: "POST",
            data: function (d) {
                d.search = $('#mainDataTable').DataTable().search(this.value);
                d.deviceId = sessionStorage.deviceId;
                d.infoType = infoType;
            }
        },
        columns: [{
            data: null,
            targets: 0
        }, {
            data: "deviceId"

        }, {
            data: "infoType",
            render: function (data, type, row) {
                if (data == 1) return "应急变化报警消息";
                else return "线路检测状态消息";
            }
        }, {
            data: "deviceId",
            render: function (data, type, row) {
                if (row.infoType == 1)
                    return "EC" + row.portSequence;
                else
                    return "SF" + row.stateSequence + "," + row.meterValueSequence;
            }
        }, {
            data: "ipAddressFrom"
        }, {
            data: "portFrom"
        }, {
            data: "ipAddressTo"
        }, {
            data: "portTo"
        }, {
            data: "timeStampCode",
            render: function (data, type, row) {
                return formatDateTime(data * 1000);
            }
        }, {
            data: "createTime",
            render: function (data, type, row) {
                if (data.length <= 10)
                    return formatDateTime(data * 1000);
                else
                    return data;
            }

        }],
        columnDefs: [{
            targets: [2, 3],
            createdCell: function (td, cellData, rowData, row, col) {
                if (rowData.infoType == 1) {
                    $(td).css('background', '#FFC107')
                }
            }
        }],
        dom: "<'row'<'col-sm-2'l><'#timer.col-md-2'><'#mainToolbar.col-md-8'>r>t<'row'<'col-md-5'i><'col-md-7'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#timer").empty();
            var strTime = "<div class='pull-left'>定时&nbsp;" +
                "<input class='form-control' id='timerValue' style='width: 50px' value='5'>&nbsp;S刷新&nbsp;" +
                "<button id='timerBtn' flag='1' class='pull-right btn btn-primary btn-sm btn-flat'>执行</button>" +
                "</div>";
            $("#timer").append(strTime);

            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'>" +
                "<div class='pull-left'>" +
                "<button class='btn btn-primary btn-md btn-flat' id='record'>恢复列表</button> " +
                "<button class='btn btn-primary btn-md btn-flat' onclick='gMainDT.ajax.reload(null, false);' ><i class='fa fa-refresh'></i>刷新</button> ";
            strToolBar += "<select class='form-control ' id='infoType'>" +
                "<option value=''>全部</option>" +
                "<option value='1'>报警</option>" +
                "<option value='2'>检测</option>" +
                "</select> " +
                "<div class='input-group-md' style='display:inline-block'>" +
                "<input type='text' class='form-control' style='width: 150px' id='timeLimit' placeholder='时间（默认全部）'>" +
                "<button class='btn btn-primary btn-flat btn-sm' type='button' onclick='$(this).searchDT()'>" +
                "<i class='fa fa-search'></i></button></div></div></div>";

            /*  var strToolBar = "<div class='pull-right'>" +

                  "<input type='text' class='form-control' style='width: 120px' id='searchText' placeholder='项目编号'>" +
                  "<button class='btn btn-primary btn-flat btn-sm' type='button' onclick='$(this).searchDT()'>" +
                  "<i class='fa fa-search'></i></button>"+
                  "<button type='button' id='reloadBtn' class='btn btn-primary btn-sm btn-flat'>" +
                  "<i class='fa fa-refresh'></i>刷新</button>" +
                  "</div>";*/
            $("#mainToolbar").append(strToolBar);
            // $.getOrgList();
            $("#infoType").change(function () {
                infoType = $(this).val();
                console.log(infoType)
            });

            $('#timeLimit').datepicker({
                format: 'yyyy-mm-dd',
                autoclose: true,
                todayBtn: 'linked',
                language: 'zh-CN'
            });
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });
    oTable = $('#mainDataTable').dataTable();
});

var timer;
$(document).on("click", "#timerBtn", function () {
    function reload() {
        gMainDT.ajax.reload(null, false);
    }

    var $timerBtn = $('#timerBtn');
    if ($timerBtn.html().indexOf("执行") >= 0) {
        timer = setInterval(reload, $("#timerValue").val() * 1000);
        $timerBtn.html("暂停");
    } else {
        $timerBtn.html("执行");
        window.clearTimeout(timer);
    }
});

$.Trim = function (str, is_global) {
    var result;
    result = str.replace(/(^\s+)|(\s+$)/g, "");
    if (is_global.toLowerCase() == "g") {
        result = result.replace(/\s/g, "");
    }
    return result;
};

$.fn.searchDT = function () {
    gMainDT.search($("#timeLimit").val()).draw();
};

$(document).on("click", "#reloadBtn", function () {
    gMainDT.ajax.reload(null, false);
});
$(document).on("click", "#record", function () {
    $.loadURL('报警器管理', '日志信息', 'management/alarmRecord.html', '2', '2', '2', '2', '2')
});

$(document).on("click", ".mbtn", function () {
    oTable.fnSetColumnVis($(this).attr("row"), false);//隐藏列
});

function getLocalTime(nS) {
    return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
}

$.checkChange = function () {
    var isChecked = $("#batchCheck").prop('checked');
    $("input:checkbox[id^='checkbox']").prop("checked", isChecked);
};